﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;

namespace FindMyChamp
{
    public partial class DetailsPage : PhoneApplicationPage
    {
        // Constructor
        public DetailsPage()
        {
            InitializeComponent();

            // JERRY NIXON: added enter animation
            // reveal
            Loaded += (s, e) =>
            {
                Helpers.Animate.LoadContent(this, LayoutRoot, null);
            };
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            // cancel actual back
            e.Cancel = (NavigationService.CanGoBack);

            // JERRY NIXON: added leave animation
            // hide and navigate
            Helpers.Animate.UnloadContent(this, LayoutRoot, () =>
            {
                // after hide then navigate
                NavigationService.GoBack();
            });
        }

        // When page is navigated to set data context to selected item in list
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // JERRY NIXON: changed to use ID instead of INDEX
            string _IDSTRING = "";
            if (NavigationContext.QueryString.TryGetValue("selectedItem", out _IDSTRING))
            {
                int _IDINT = int.Parse(_IDSTRING);
                DataContext = App.ViewModel.Champs.Where(x => x.ID == _IDINT).First();
            }
        }

        private void txtPhone_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            // Get our champ's name & phone number
            TextBlock tb = (TextBlock)e.OriginalSource;
            StackPanel sp = (StackPanel)tb.Parent;
            TextBlock tbFull = new TextBlock();

            foreach (UIElement uiEl in sp.Children)
            {
                if (uiEl is TextBlock)
                {
                    tbFull = (TextBlock)uiEl;
                    if (tbFull.Name == "txtFullName")
                        break;
                }
            }

            // Perform our phone call
            PhoneCallTask phoneCallTask = new PhoneCallTask();
            phoneCallTask.PhoneNumber = tb.Text;
            phoneCallTask.DisplayName = tbFull.Text;
            phoneCallTask.Show();
        }

        private void txtEmail_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            TextBlock tb = (TextBlock)e.OriginalSource;

            // Perform our email task
            EmailComposeTask emailComposeTask = new EmailComposeTask();
            emailComposeTask.To = tb.Text;
            emailComposeTask.Subject = "I <3 Find My Champ";
            emailComposeTask.Show();
        }

        private void txtBlog_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            TextBlock tb = (TextBlock)e.OriginalSource;
            Uri blogUri;

            if (Uri.TryCreate(tb.Text, UriKind.RelativeOrAbsolute, out blogUri))
            {
                // Launch the blog in browser
                webBrowserTask.Uri = blogUri;
                webBrowserTask.Show();
            }
        }

        private void txtTwitter_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            TextBlock tb = (TextBlock)e.OriginalSource;
            Uri twitterUri;

            if (Uri.TryCreate("http://mobile.twitter.com/" + tb.Text, UriKind.RelativeOrAbsolute, out twitterUri))
            {

                // Launch the blog in browser
                webBrowserTask.Uri = twitterUri;
                webBrowserTask.Show();
            }
        }

		void saveContactTask_Completed(object sender, SaveContactResult e)
		{
			switch (e.TaskResult)
			{
				case TaskResult.OK:
					MessageBox.Show("Your champ has been added as a contact on your phone.");
					break;

				case TaskResult.Cancel:
					MessageBox.Show("Add champ canceled.");
					break;

				case TaskResult.None:
					MessageBox.Show("Champ could not be saved.");
					break;
			}
		}

		private void AddContact_Click(object sender, EventArgs e)
		{
			try
			{
				SaveContactTask saveContactTask = new SaveContactTask();
				saveContactTask.Completed += new EventHandler<SaveContactResult>(saveContactTask_Completed);

				WPChamp champ = this.DataContext as WPChamp;

				if( champ != null )
				{
					saveContactTask.FirstName = champ.FirstName;
					saveContactTask.LastName = champ.LastName;
					saveContactTask.MobilePhone = champ.Phone;
					
					if( !string.IsNullOrEmpty(champ.Email) )
					{
						saveContactTask.WorkEmail = champ.Email;
					}

					if (!string.IsNullOrEmpty(champ.Blog))
					{
						saveContactTask.Website = champ.Blog;
					}

					if (!string.IsNullOrEmpty(champ.Twitter))
					{
						saveContactTask.Notes = champ.Twitter;
					}

					saveContactTask.Show();
				}
			}
			catch (System.InvalidOperationException)
			{
				MessageBox.Show("Unable to save your champ.");
			}
		}
    }
}